#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 11/13/2019 10:57 AM
from concurrent.futures import ThreadPoolExecutor
from lib.plugins import get_server_info
import paramiko
import requests
from lib.plugins import get_server_info
from concurrent.futures import ThreadPoolExecutor

import settings


def ssh_func(hostname, command):
    """
    通过 paramiko 连接远程主机，并执行指定的命令
    :param hostname:hostname 主机ip
    :param command:要执行的指令
    :return: 返回执行指令后返回的信息
    """
    private_key = paramiko.RSAKey.from_private_key_file(settings.SSH_PRIVATE_KEY_PATH, password='zjgisadmin')
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, port=settings.SSH_PORT, username=settings.SSH_USER, pkey=private_key)
    stdin, stdout, stderr = ssh.exec_command(command)
    result = stdout.read()
    ssh.close()
    return result.decode('utf-8')

def salt(hostname,command):
    """"""
    """
        import salt.client
        local = salt.client.LocalClient()
        result = local.cmd(hostname, 'cmd.run', [command,])
        return result['hostname']
    """
    import subprocess
    cmd = "salt '%s' cmd.run '%s' " %(hostname,command)
    data = subprocess.getoutput(cmd)
    return data


def task(hostname):
    # 要执行的任务
    if settings.MODE == 'SSH':
        info = get_server_info(hostname, ssh_func)
    elif settings.MODE == 'SALT':
        info = get_server_info(hostname, salt)
    else:
        raise Exception('模式输入错误，请修改')

    info['hostname'] = hostname
    print(info)

    requests.post(url="http://127.0.0.1:8000/api/v1/server/",
                  json=info)


def run():
    response = requests.get(url="http://127.0.0.1:8000/api/v1/server/")
    host_list = response.json()
    pool = ThreadPoolExecutor(settings.THREAD_POOL_SIZE)
    for hostname in host_list:
        pool.submit(task, hostname)


if __name__ == '__main__':
    run()
